package com.company.wechatpush.controller;

import com.company.wechatpush.entity.Result;
import com.company.wechatpush.service.LocationService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

/**
 * @author Real
 * @since 2022-09-03 1:32 AM
 */
@RestController
public class LocationController {

    /**
     * <xml>
     * <ToUserName><![CDATA[toUser]]></ToUserName>
     * <FromUserName><![CDATA[fromUser]]></FromUserName>
     * <CreateTime>123456789</CreateTime>
     * <MsgType><![CDATA[event]]></MsgType>
     * <Event><![CDATA[LOCATION]]></Event>
     * <Latitude>23.137466</Latitude>
     * <Longitude>113.352425</Longitude>
     * <Precision>119.385040</Precision>
     * </xml>
     * 接收用户的地理位置信息
     *
     * @param input 接收到对应的 xml 文件数据
     * @return 获取到对应的区号 distict_id
     */
    @RequestMapping("/location")
    public Result<String> receiveLocation(@RequestParam String input) throws DocumentException, XPathExpressionException {
        Document document = DocumentHelper.parseText(input);
        XPathFactory factory = XPathFactory.newInstance();
        XPath path = factory.newXPath();
        XPathExpression latitudeCompile = path.compile("/xml/Latitude");
        XPathExpression longitudeCompile = path.compile("/xml/Longitude");
        String latitude = latitudeCompile.evaluate(document);
        String longitude = longitudeCompile.evaluate(document);
        return LocationService.getLocationCode(latitude, longitude);
    }

}
